<?php

namespace app\services;

use EasyWeChat\Factory;
use plugin\admin\app\model\Good;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\Order;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class WechatPayService
{

    public static function index($request)
    {
        $config = self::getConfig();
        $app = Factory::officialAccount($config);
        $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
        $symfony_request->headers = new HeaderBag($request->header());
        $app->rebind('request', $symfony_request);

        $response = $app->server->serve();
        return $response->getContent();
    }


    public static function getConfig()
    {
//        $config = Option::where('name', 'wechatPayInfo')->value('value');
//        $wechat = Option::where('name', 'wechat')->value('value');
//        $wechat = json_decode($wechat, true);
//        $config = json_decode($config, true);
        $config = [
            'app_id' => 'wx195e01f1f1d1aed9',
            'mch_id' => '1603067830',
            'key' => 'VyB0Qyx3Fu48jP5tL1zm29A4VBQCAnPy',

            'notify_url' => 'https://car.ydk1.cn/wechat/notify',
        ];
        return $config;
    }

    // 初始化
    public static function init()
    {
        $config = self::getConfig();
        $app = Factory::payment($config);
        $app = $app->setSubMerchant('1708900669','wx4480f39c73c3d434');
        return $app;
    }

    public static function orderUnify($openid,$goods_id,$order)
    {
        $app = self::init();
        $goods = Good::where('id',$goods_id)->first();
        $data = $app->order->unify([
            'body' => $goods->name,
            'out_trade_no' => $order['sn'],
            'total_fee' => $goods->price * 100,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'sub_openid' => $openid,
        ]);
        if (!isset($data['prepay_id']) || $data['result_code']=='FAIL'){
            return false;
        }
        $prepayId = $data['prepay_id']??'';
        if (!empty($prepayId)){
            $config = self::getConfig();
            $payment = Factory::payment($config);

            $jssdk = $payment->jssdk;
            $json = $jssdk->bridgeConfig($prepayId);
            return $json;
        }
    }



    public static function notify($request)
    {
        $app = self::init();
        $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
        $symfony_request->headers = new HeaderBag($request->header());
        $app->rebind('request', $symfony_request);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            dump($message);
           $order = Order::where('sn', $message['out_trade_no'])->first();
            if (!$order || $order->is_pay == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $order->pay_time = date('Y-m-d H:i:s'); // 更新支付时间为当前时间
                    $order->is_pay = 1;
                    $order->pay_no = $message['transaction_id'];
                    RedisQueue::orderNotify(['sn'=>$order->sn]);
                    $order->save();
                    return true;
                }
            }
            return $fail('通信失败，请稍后再通知我');
        });
        return $response;

    }

    public function jsPay()
    {
        $config = [
            // 前面的appid什么的也得保留哦
            'app_id'             => 'xxxx',
            'mch_id'             => 'your-mch-id',
            'key'                => 'key-for-signature',
            'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
            'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
            // 'device_info'     => '013467007045764',
            // 'sub_app_id'      => '',
            // 'sub_merchant_id' => '',
            // ...
        ];



    }

}